<?php

/**
 * @property PDO $conn
 */
class MysqlDatabase extends ADatabase
{
	protected function __construct() { }
	/**
	 * @return string[]
	 */
	 
	public function getDatabases()
	{
		$schema = array();
		$query  = "SHOW DATABASES";
		$stmt = $this->conn->prepare($query);
		if($stmt->execute())
		{
			while($row = $stmt->fetch(\PDO::FETCH_NUM))
			{
				$schema[] = $row[0];
			}
		}
		return $schema;
	}
	
	/**
	 * @return string[]
	 */
	public function getTables($database)
	{
		$tables = array();
		$query  = "SHOW FULL TABLES IN $database";
		$stmt = $this->conn->prepare($query);
		if($stmt->execute())
		{
			while($row = $stmt->fetch(\PDO::FETCH_NUM))
			{
				$tables[] = $row[0];
			}
		}
		return $tables;
	}
	
	
	public function getQueryResult($query)
	{
		$calcFoundRows = false;
		if(preg_match('/^\s*\(*SELECT/i', $query))
		{
			if(stripos($query, "SQL_CALC_FOUND_ROWS") === false)
			{
				$query = preg_replace('/^\s*\(*SELECT/i', "$0 SQL_CALC_FOUND_ROWS", $query, 1);
				$calcFoundRows = true;
			}
		}
		$result = parent::getQueryResult($query);
		if($calcFoundRows)
		{
			$stmt = $this->conn->prepare("SELECT FOUND_ROWS()");
			$stmt->execute();
			$i = $stmt->fetchColumn();
			if(strlen($i)) $result->foundRows = (int)$i;
		}
		return $result;
	}
	
	public function useDatabase($database)
	{
		$this->conn->query("USE $database;");
	}
	public function mainPanelServer(ConfigServer $server)
	{
		$this->getQueryResult("SHOW DATABASES")->displayResult();
	}
	public function mainPanelDatabase($database)
	{
		$this->getQueryResult("SHOW TABLE STATUS")->displayResult();
	}
	public function tableColumns($database, $table)
	{
		return $this->getQueryResult("SHOW FULL COLUMNS \nFROM `$table` \nIN `$database`");
	}
	public function tableIndexes($database, $table)
	{
		return $this->getQueryResult("SHOW INDEX FROM $table FROM $database");
	}
	/**
	 * @return DatabaseResult
	 */
	public function browseResult($database, $table, $perPage = 100, $page = 1)
	{
		return $this->getQueryResult("SELECT * \nFROM $database.$table \nLIMIT $perPage");
	}
	
	
}